/*
    Author    :Arrow
    CreateTime:2009-06-01 12:48:25
*/
package system.base;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import system.imp.GWException;
import system.imp.GWFileUploadProcessor;
import system.imp.PoiUtil;


import framework.core.*;

public class InputDataSrv extends IHandler
{

	public InputDataSrv() 
	{
		super();
	}
    
    //下载供应商信息
    private void doDownProviderData(SrvContext context) throws Exception{
        DataInputStream dis = null;
        FileOutputStream fos = null;
        
        try{
          String tDay = system.imp.DateUtil.getNextUpDay(-1);
          //文件下载
          String Name="GW_Provider_"+tDay+".xls";
          String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
          System.out.println(strFilePath);
          URL url = new URL(strFilePath);
              
          dis = new DataInputStream(url.openStream());
         
          File f2 = new File(Config.getGSSavePath() +"/" + Name);
          
          if(!f2.exists()) f2.createNewFile();
          fos = new FileOutputStream(f2);
                      
          byte[] buffer = new byte[512];
          int length = 0;
          while((length = dis.read(buffer,0,512))!=-1){
              fos.write(buffer,0,length);
          }
          
          fos.flush();
          fos.close();
          dis.close();
          
          context.setValue("filename",Name);
      }
      catch(IOException ioe){
          ioe.printStackTrace();
          throw new GWException(GWException.E17792,GWException.E17792_MSG);
      }
    }
	
    //导入供应商信息
    public void doInputProviderData(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception{
        String tResult="";
        DataInputStream dis = null;
        
        String tDay = system.imp.DateUtil.getNextUpDay(-1);
        //文件下载
        String Name="GW_Provider_"+tDay+".xls";
        String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
        System.out.println(strFilePath);
        URL url = new URL(strFilePath);
        
        dis = new DataInputStream(url.openStream());
        
        try{
            //导入商户信息
            tResult = GWFileUploadProcessor.batchImportProvider(dis, con, loginContext);
        }catch(GWException e){
            context.setErrorMsg(e.getMessage());                
            throw new GWException(e.getMessage());
        }finally{
            if (dis != null) dis.close(); 
        }
        
        //从返回的值中取得失败和成功的数据
        if (context != null)
        {
            String tSuccess= tResult.split("-")[0];
            String tFail= tResult.split("-")[1];
            String tOutputPath = tResult.split("-")[2];
            context.setValue("success",tSuccess);
            context.setValue("fail",tFail);
            if(Integer.parseInt(tFail)>0){
                context.setValue("faildown",tOutputPath);
                if("0".equals(tOutputPath))
                    context.setValue("faildownfailure","");
            }
        }
    }
    
    //下载产品信息
    private void doDownProductData(SrvContext context) throws Exception{
        DataInputStream dis = null;
        FileOutputStream fos = null;
        
        try{
          String tDay = system.imp.DateUtil.getNextUpDay(-1);
          
          //文件下载
          String Name="GW_Manufacture_"+tDay+".xls";
          String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
          System.out.println(strFilePath);
          URL url = new URL(strFilePath);

          dis = new DataInputStream(url.openStream());
         
          File f2 = new File(Config.getGSSavePath() +"/" + Name);
          
          if(!f2.exists()) f2.createNewFile();
          fos = new FileOutputStream(f2);
                      
          byte[] buffer = new byte[512];
          int length = 0;
          while((length = dis.read(buffer,0,512))!=-1){
              fos.write(buffer,0,length);
          }
          
          fos.flush();
          fos.close();
          dis.close();
          
          context.setValue("filename",Name);
      }
      catch(IOException ioe){
          ioe.printStackTrace();
          throw new GWException(GWException.E17792,GWException.E17792_MSG);
      }
    }
    
    //导入产品信息
    public void doInputProductData(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception{
        String tResult="";
        DataInputStream dis = null;
        
        String tDay = system.imp.DateUtil.getNextUpDay(-1);
        //文件下载
        String Name="GW_Manufacture_"+tDay+".xls";
        String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
        System.out.println(strFilePath);
        URL url = new URL(strFilePath);
        
        dis = new DataInputStream(url.openStream());
        
        try{
            //导入产品信息
            tResult = GWFileUploadProcessor.batchImportManufacture(dis, con, loginContext);
        }catch(GWException e){
            context.setErrorMsg(e.getMessage());    
            throw new GWException(e.getMessage());
        }finally{
            if (dis != null) dis.close(); 
        }
        
        //从返回的值中取得失败和成功的数据
        if (context != null)
        {
            String tSuccess= tResult.split("-")[0];
            String tFail= tResult.split("-")[1];
            String tOutputPath = tResult.split("-")[2];
            context.setValue("success",tSuccess);
            context.setValue("fail",tFail);
            if(Integer.parseInt(tFail)>0){
                context.setValue("faildown",tOutputPath);
                if("0".equals(tOutputPath))
                    context.setValue("faildownfailure","");
            }
        }
    }
    
    //下载产品分类信息
    private void doDownCategoryData(SrvContext context) throws Exception{
        DataInputStream dis = null;
        FileOutputStream fos = null;
        
        try{
          String tDay = system.imp.DateUtil.getNextUpDay(-1);
          
          //文件下载
          String Name="GW_ManufactureCategory_"+tDay+".xls";
          String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
          System.out.println(strFilePath);
          URL url = new URL(strFilePath);

          dis = new DataInputStream(url.openStream());
         
          File f2 = new File(Config.getGSSavePath() +"/" + Name);
          
          if(!f2.exists()) f2.createNewFile();
          fos = new FileOutputStream(f2);
                      
          byte[] buffer = new byte[512];
          int length = 0;
          while((length = dis.read(buffer,0,512))!=-1){
              fos.write(buffer,0,length);
          }
          
          fos.flush();
          fos.close();
          dis.close();
          
          context.setValue("filename",Name);
      }
      catch(IOException ioe){
          ioe.printStackTrace();
          throw new GWException(GWException.E17792,GWException.E17792_MSG);
      }
    }
    
    //导入产品分类信息
    public void doInputCategoryData(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception{
        String tResult="";
        DataInputStream dis = null;
        
        String tDay = system.imp.DateUtil.getNextUpDay(-1);
        //文件下载
        String Name="GW_ManufactureCategory_"+tDay+".xls";
        String strFilePath = "http" + "://" + Config.getGSIP() + ":" +Config.getGSPort() + Config.getGSContext() + "/" + Name;
        System.out.println(strFilePath);
        URL url = new URL(strFilePath);
        
        dis = new DataInputStream(url.openStream());
        
        try{
            //导入产品信息
            tResult = GWFileUploadProcessor.batchImportManufactureCategory(dis, con, loginContext);
        }catch(GWException e){
            context.setErrorMsg(e.getMessage());    
            throw new GWException(e.getMessage());
        }finally{
            if (dis != null) dis.close(); 
        }
        
        //从返回的值中取得失败和成功的数据
        if (context != null)
        {
            String tSuccess= tResult.split("-")[0];
            String tFail= tResult.split("-")[1];
            String tOutputPath = tResult.split("-")[2];
            context.setValue("success",tSuccess);
            context.setValue("fail",tFail);
            if(Integer.parseInt(tFail)>0){
                context.setValue("faildown",tOutputPath);
                if("0".equals(tOutputPath))
                    context.setValue("faildownfailure","");
            }
        }
    }
    
    public void doInputWorldExplorerBusData(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception
    {
        String warehouseCode = loginContext.getLoginWarehouseCode();
        String title = "";
        
        FileOutputStream fos = null;
                
        String info = "";
        FileHolder file = context.getFile("ItemFile");
        
        WorldExp wExp = WorldExp.fetch();
        InputStream stream = new java.io.ByteArrayInputStream(file.getBytes());
        
        POIFSFileSystem f = new POIFSFileSystem(stream);
        HSSFWorkbook wb = new HSSFWorkbook(f);
        HSSFSheet sheet = wb.getSheetAt(0);     
        HSSFRow row = null;
        HSSFCell cell = null ;
        
        Iterator ir = sheet.rowIterator();
        ArrayList list = new ArrayList();
        int rowCount = 0;
        int cellCount = 0 ;
        while(ir.hasNext())
        {
            row = (HSSFRow)ir.next();
            rowCount++;
            
            cellCount = row.getPhysicalNumberOfCells();
                for(int i = 0; i < cellCount; i++)
                {
                    //读取Title
                    if(rowCount == 1 && i == 0){
                        try{
                            title = PoiUtil.getCellValue(row,i,"").trim();
                            String billTypeCode = WorldExp.getBillTypeCode(title);
                            String billType = WorldExp.getBillType(billTypeCode);
                            wExp.setBillTypeCode(billTypeCode);
                            wExp.setBillType(billType);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件标题错误,请核对!");
                            return;
                        }
                        break;
                    }
                    //读取材料清单编号
                    else if(rowCount == 2 && i == 9){
                        try{
                            String materialCode = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setMaterialCode(materialCode);
                            if("".equals(materialCode)){
                                stream.close();
                                context.setErrorMsg("上传文件材料清单号错误,请核对!");
                                return;
                            }
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件材料清单号错误,请核对!");
                            return;
                        }
                        break;
                    }
                    //读取结算单编号
                    else if(rowCount == 3 && i == 9)
                    {
                        try{
                            String balanceCode = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setBalanceCode(balanceCode);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件结算单号错误,请核对!");
                            return;
                        }
                    }
                    //公司名称
                    else if(rowCount == 4 && i == 1){
                        try{
                            String warehouseName = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setWarehouseName(warehouseName);
                            String warehouseJTCode = WorldExp.getWarehouseJTCode(warehouseName);
                            wExp.setWarehouseCode(warehouseJTCode);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件公司名称错误,请核对!");
                            return;
                        }
                    }
                    //车辆自编号
                    else if(rowCount == 4 && i == 3){
                        try{
                            String busCode = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setBusCode(busCode);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件车辆自编号错误,请核对!");
                            return;
                        }
                    }
                    //进场年月日
                    else if(rowCount == 4 && i == 5){
                        try{
                            String in_year = PoiUtil.getCellValue(row, i, "").trim();
                            String in_month = PoiUtil.getCellValue(row, 7, "").trim();
                            String in_day = PoiUtil.getCellValue(row, 9, "").trim();
                            if(in_month.trim().length() == 1) in_month = "0" + in_month.trim();
                            if(in_day.trim().length() == 1) in_day = "0" + in_day.trim();
                            String inDate = in_year + "-" + in_month + "-" + in_day;
                            wExp.setInDate(inDate);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件进场日期错误,请核对!");
                            return;
                        }
                        break;
                    }
                    //车型
                    else if(rowCount == 5 && i == 1){
                        try{
                            String busType = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setBusType(busType);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件车型错误,请核对!");
                            return;
                        }
                    }
                    //拍照号码
                    else if(rowCount == 5 && i == 3){
                        try{
                            String pzCode = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setPzCode(pzCode);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件车辆牌照错误,请核对!");
                            return;
                        }
                    }
                    //出场年月日
                    else if(rowCount == 5 && i == 5){
                        try{
                            String out_year = PoiUtil.getCellValue(row, i, "").trim();
                            String out_month = PoiUtil.getCellValue(row, 7, "").trim();
                            String out_day = PoiUtil.getCellValue(row, 9, "").trim();
                            if(out_month.trim().length() == 1) out_month = "0" + out_month.trim();
                            if(out_day.trim().length() == 1) out_day = "0" + out_day.trim();
                            String outDate = out_year + "-" + out_month + "-" + out_day;
                            wExp.setOutDate(outDate);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件出厂日期错误,请核对!");
                            return;
                        }
                        break;
                    }
                    
                    //路线
                    else if(rowCount == 6 && i == 1){
                        try{
                            String line = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setLine(line);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件线路错误,请核对!");
                            return;
                        }
                    }
                    //质量检验员
                    else if(rowCount == 6 && i == 3){
                        try{
                            String checkPerson = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setCheckPerson(checkPerson);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件质量检验员错误,请核对!");
                            return;
                        }
                    }
                    //结算员
                    else if(rowCount == 6 && i == 5){
                        try{
                            String balancePerson = PoiUtil.getCellValue(row, i, "").trim();
                            wExp.setBalancePerson(balancePerson);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件结算员错误,请核对!");
                            return;
                        }
                    }
                    //公里数
                    else if(rowCount == 6 && i == 9){
                        try{
                            String skilo = PoiUtil.getCellValue(row, i, "").trim().trim();
                            double kilo = Double.parseDouble(skilo);
                            wExp.setKilo(kilo);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件公里数错误,请核对!");
                            return;
                        }
                        break;
                    }
                    
                    //工时费
                    else if(rowCount == 7 && i == 1){
                        try{
                            double gsPrice = Double.parseDouble(PoiUtil.getCellValue(row, i, "").trim());
                            wExp.setGsPrice(gsPrice);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件工时费错误,请核对!");
                            return;
                        }
                    }
                    //材料费
                    else if(rowCount == 7 && i == 3){
                        try{
                            double materialPrice = Double.parseDouble(PoiUtil.getCellValue(row, i, "").trim());
                            wExp.setMaterialPrice(materialPrice);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件材料费错误,请核对!");
                            return;
                        }
                    }
                    //公里数
                    else if(rowCount == 7 && i == 5){
                        try{
                            double wjgPrice = Double.parseDouble(PoiUtil.getCellValue(row, i, "0").trim());
                            wExp.setWjgPrice(wjgPrice);
                        }
                        catch(Exception e){
                            stream.close();
                            context.setErrorMsg("上传文件公里数错误,请核对!");
                            return;
                        }
                        break;
                    }
                }
        }
        wExp.setUploadPersonId(loginContext.getLoginUserId());
        wExp.setUploadPerson(loginContext.getLoginUserName());
        String uploadTime = new DateUtil().getFullString();
        wExp.setUploadTime(uploadTime);
        
        stream.close();
        
        
        stream = new java.io.ByteArrayInputStream(file.getBytes());
                
        String fileName = file.getFileName();
        String strPath = context.m_req.getRealPath("/");
        if (!strPath.endsWith("\\"))
        {
            strPath +="\\";
        }
        
        String subPath = getWorldExprolerSubPath(warehouseCode, title);
        
        String strSavePath = ConstDefine.EXCELFILE_WROLDEXPROLOR_SAVEPATH;
        System.out.println("===========================UploadFilePath:" + strPath + strSavePath + fileName);
        String filePathAndName = strPath + strSavePath + subPath + fileName;
        
        wExp.setFileName(fileName);
        wExp.setFilePath(strSavePath + subPath + fileName);
                
        File f2 = new File(filePathAndName);
        if(!f2.exists()){
            f2.createNewFile();
            wExp.save(con);
        }
        else{
            stream.close();
            context.setErrorMsg("文件已经存在,请核对!");
            return;
        }
        fos = new FileOutputStream(f2);
        
        byte[] buffer = new byte[512];
        int length = 0;
        while((length = stream.read(buffer,0,512))!=-1){
            fos.write(buffer,0,length);
        }
        
        
        fos.flush();
        fos.close();
        stream.close();
        
        context.setErrorMsg("[" + fileName + "]文件上传成功!");
    }
    
	public void doAction(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String action_code = context.getActionCode();
		String path = "/system/base/";
		
        if (action_code.equalsIgnoreCase("toBackInputData"))
        {
            context.setNextUrl(path + "InputDataIndex.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toDownProviderData")){
            doDownProviderData(context);
            context.setNextUrl(path + "ProviderDownView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toInputProviderData")){
            doInputProviderData(con, context, loginContext);
            context.setNextUrl(path + "ProviderUploadView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toDownProductData")){
            doDownProductData(context);
            context.setNextUrl(path + "ProductDownView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toInputProductData")){
            doInputProductData(con, context, loginContext);
            context.setNextUrl(path + "ProductUploadView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toDownCategoryData")){
            doDownCategoryData(context);
            context.setNextUrl(path + "CategoryDownView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("toInputCategoryData")){
            doInputCategoryData(con, context, loginContext);
            context.setNextUrl(path + "CategoryUploadView.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("importWroldExplorerBusData")){
            doInputWorldExplorerBusData(con, context, loginContext);
            context.setNextUrl(path + "InputWorldExpDataIndex.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("enterWroldExplorerBusData")){
            context.setNextUrl(path + "InputWorldExpDataIndex.jsp");
            return;
        }
	
		Logger.throwException("InputDataSrv","unknown action_code="+action_code);
	}
	
	private String getWorldExprolerSubPath(String warehouseCode, String title){
	    String ret = "";
	    if(warehouseCode == null) return ret;
	    if("".equals(warehouseCode.trim())) return ret;
	    if(title == null) return ret;
        if("".equals(title.trim())) return ret;
	    
        if("00".equals(warehouseCode)){ //总库
            ret += "00\\";
        }
        if("0000".equals(warehouseCode)){ //总库
            ret += "00\\";
        }
        else if("000002".equals(warehouseCode)){ //一汽
            ret += "02\\";
        }
        else if("00000200".equals(warehouseCode)){ //一汽
            ret += "02\\";
        }
        else if("000001".equals(warehouseCode)){ //巴士新新
            ret += "01\\";
        }
        else if("00000100".equals(warehouseCode)){ //巴士新新
            ret += "01\\";
        }
        else if("00000101".equals(warehouseCode)){ //巴士新新
            ret += "01\\";
        }
        else if("00000102".equals(warehouseCode)){ //巴士新新
            ret += "01\\";
        }
        else if("000004".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("00000400".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("0000040000".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("0000040001".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("00000401".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("0000040100".equals(warehouseCode)){ //电车公司
            ret += "04\\";
        }
        else if("000006".equals(warehouseCode)){ //宝山
            ret += "06\\";
        }
        else if("00000600".equals(warehouseCode)){ //宝山
            ret += "06\\";
        }
        else if("000003".equals(warehouseCode)){ //巴士四汽
            ret += "03\\";
        }
        else if("000005".equals(warehouseCode)){ //浦东
            ret += "05\\";
        }
        else if("000007".equals(warehouseCode)){ //上南
            ret += "07\\";
        }
        else if("000008".equals(warehouseCode)){ //高联
            ret += "08\\";
        }
        else if("000009".equals(warehouseCode)){ //大众西南
            ret += "09\\";
        }
        else if("000010".equals(warehouseCode)){ //大众西北
            ret += "10\\";
        }
        else if("000011".equals(warehouseCode)){ //大众巴士
            ret += "11\\";
        }
        else if("000012".equals(warehouseCode)){ //大众百通
            ret += "12\\";
        }
        else if("000013".equals(warehouseCode)){ //崇明大众
            ret += "13\\";
        }
        else if("000014".equals(warehouseCode)){ //申新巴士
            ret += "14\\";
        }
        else if("000015".equals(warehouseCode)){ //金山大众
            ret += "15\\";
        }
        else if("000016".equals(warehouseCode)){ //奉贤大众
            ret += "16\\";
        }
        else if("000017".equals(warehouseCode)){ //五汽公交
            ret += "17\\";
        }
        else if("000018".equals(warehouseCode)){ //强生公交
            ret += "18\\";
        }
        
        if(title.startsWith("发动机")){
            ret += "01\\";
        }
        else if(title.startsWith("内车身")){
            ret += "03\\";
        }
        else if(title.startsWith("外车身")){
            ret += "02\\";
        }
        
	    return ret;
	}
		
}
